<?php
use OSS\OssClient;

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Lib/Base.php';
require_once __DIR__ . '/funcs.php';
require_once __DIR__ . '/Lib/Page.php';

checkLogin();
checkFunc(74);

$now = time();
$success = $_GET['success'] ?? null;
$error = $_GET['error'] ?? null;
$action = $_GET['action'] ?? null;

$coupon = $DB->select('red_packet_coupon', '*', ['ORDER'=>['id'=>'DESC']]);

$action = $_GET['action'] ?? null;
if($action == 'upload') {
    checkFunc(75, '权限不足，无法操作');

    try {
        $ossclient = new OssClient($akid, $aksec, $endpoint);
        $bucket = 'kdwawajistatic';
        $name_arr = explode('.', $_FILES['file']['name']);
        $fext = $name_arr[count($name_arr)-1];
        $file_name = 'coupon_' . date('YmdHis').'_'.mt_rand(100000,999999).'.'.$fext;
        $object = 'damai/lyfen/couponImage/' . $file_name;
        $filePath = $_FILES['file']['tmp_name'];
        $ossclient->uploadFile($bucket, $object, $filePath);
    } catch(\Exception $e) {
        echo 'BAD|上传OSS文件失败';
        exit;
    }
    echo 'OK|'.$file_name;
    exit;
}
else if($action == 'new') {
    checkFunc(75, '权限不足，无法操作');
    // var_dump($_POST);exit;
    // $filename = $_POST['oss_filename'] ?? '';
    $name = $_POST['coupon_name'] ?? '';
    $batch_number = trim($_POST['batch_number'] ?? '');
    $jump_url = trim($_POST['jump_url'] ?? '');
    // if(!$filename) goExit('red_packet_coupon.php?error=图片未上传');
    $edit_id = $_POST['edit_id'] ?? 0;
    $inventory_max = $_POST['inventory_max'] ?? 0;
    $inventory = $_POST['inventory'] ?? 0;
    $total_amount = $_POST['total_amount'] ?? 0;
    $discount_amount = $_POST['discount_amount'] ?? 0;
    $data = [
        'coupon_name' => $name,
        // 'coupon_url' => $CDN_URL . '/couponImage/' . $filename,
        'create_time' => $now,
        'batch_number' => $batch_number,
        'jump_url' => $jump_url,
        'inventory_max' => $inventory_max,
        'inventory' => $inventory,
        'total_amount' => $total_amount,
        'discount_amount' => $discount_amount
    ];
    // var_dump($data);exit;
    if (!$edit_id){
        $DB->insert('red_packet_coupon', $data);
        $id = $DB->id();
        if(!$id) goExit('优惠券添加失败，请联系管理员');
        // operate_log('coupon', 'new_coupon', ['coupon_ID'=>$id, '图片地址'=>$CDN_URL . '/couponImage/' . $filename]);
        $msg = '添加成功!';
    }else{
        // unset($data['inventory']);
        $DB->update('red_packet_coupon',$data,['id' => $edit_id]);
        $msg = '修改成功!';
    }
    goExit('red_packet_coupon.php?success=优惠券'.$msg);
}
else if($action == 'del') {
    checkFunc(75, '权限不足，无法操作');
    $tid = $_GET['tid'] ?? null;
    if(!$tid) goExit('red_packet_coupon.php?error=无效的任务ID');
    $save = $DB->delete('red_packet_coupon',['id'=>$tid]);
    operate_log('banner', 'delete_banner', ['Banner_ID'=>$tid]);
    goExit('red_packet_coupon.php?success=删除成功!');
}

display_header();
?>
<link href="css/jquery.dm-uploader.min.css" rel="stylesheet">
<style>
    .valid_task {background:#ffe; /* #C2ECA7 */;}
    #fileinp{
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
    }
</style>

<section class="content">

    <?php display_title('优惠券管理'); ?>

    <?php if($error) : ?>
        <div class="alert alert-warning alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <span><?php echo $error; ?></span>
        </div>
    <?php endif ?>
    <?php if($success) : ?>
        <div class="alert alert-success alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            <h4><i class="icon fa fa-check"></i> 成功</h4>
            <?php echo $success; ?>
        </div>
    <?php endif ?>

    <div class="box box-warning">
        <div class="box-header with-border">
            <h3 class="box-title"><i class="fa fa-tasks"></i> 优惠券列表</h3>
            <span style="margin-left:20px;">
                <button class="btn btn-primary new_banner">添加优惠券</button>
            </span>
        </div>
        <div class="box-body">
            <table id="logtable" class="table table-bordered table-striped dataTable table-hover table-condensed" role="grid" aria-describedby="example1_info">
                <thead>
                <tr>
                    <th class="center" width="60">ID</th>
                    <th class="center" width="100">名称</th>
                    <th class="center" width="100">总金额</th>
                    <th class="center" width="100">优惠金额</th>
                    <th class="center" width="150">批次号</th>
                    <th class="center" width="100">跳转链接</th>
                    <th class="center" width="100">设置库存</th>
                    <th class="center" width="100">剩余库存</th>
                    <th class="center" width="160">添加时间</th>
                    <th class="center">操作</th>
                </tr>
                </thead>
                <tbody>
                <?php
                foreach($coupon as $banner) {
                    ?>
                    <tr role="row" style="height:38px;text-align:center;">
                        <td class="font12">
                            <span class="tid" style="font-size:16px;font-weight:bold;"><?php echo $banner['id']; ?></span>
                        </td>
                        <td class="tname"><?php echo $banner['coupon_name']; ?></td>
                        <td class="total_amount"><?php echo $banner['total_amount']; ?></td>
                        <td class="discount_amount"><?php echo $banner['discount_amount']; ?></td>
                        <td class="batch"><?php echo $banner['batch_number']; ?></td>
                        <td class="jump"><?php echo $banner['jump_url']; ?></td>
                        <td class="inventory_max"><?php echo $banner['inventory_max']; ?></td>
                        <td class="inventory"><?php echo $banner['inventory']; ?></td>
                        <td class="font12"><?php echo date('Y-m-d H:i:s', $banner['create_time']); ?></td>
                        <td class="left" style="padding:0;padding-left:15px;" tid="<?php echo $banner['id']; ?>">
                            <button type="button" class="btn btn-sm btn-success edit_coupon">修改</button> |
                            <button class="btn btn-danger btn-sm del_banner">删除</button>
                        </td>
                    </tr>
                <?php } ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 添加Banner -->
    <div class="modal fade" id="modal-add-banner">
        <div class="modal-dialog modal-lg">
            <form id="new_banner_form" action="red_packet_coupon.php?action=new" method="post">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">添加一个优惠券</h4>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" id="edit_id" name="edit_id" value="" />
                        <table border="0" width="100%" class="modal_table_style">
                            <tr height="45">
                                <th style="text-align:right;padding-right:10px;">名称:</th>
                                <td><input type="text" class="form-control" size="20" name="coupon_name" id="name" /></td>
                            </tr>
                            <tr height="45">
                                <th style="text-align:right;padding-right:10px;">批次号:</th>
                                <td><input type="text" class="form-control" size="20" name="batch_number" id="batch_number" /></td>
                            </tr>
                            <!-- <tr height="110">
                                <th style="text-align:right;padding-right:10px;">图片:</th>
                                <td>
                                    <img style="float:left;border:0px solid #aaa;" id="avatar_preview" src="images/noimage.jpg" width="400" height="80" />
                                    <div id="drop-area" style="float:left; padding-top:40px; margin-left:20px;">
                                        <label for="fileinp">
                                            <span id="text" style="padding:10px 20px;border-radius:4px;background:#007bff;color:#fff;">请上传图片</span>
                                            <input type="file" id="fileinp" />
                                            <br />
                                            <div style="margin-top:15px;font-size:12px;font-weight:normal;" id="upload_result"></div>
                                            <input type="hidden" id="oss_filename" name="oss_filename" value="" />
                                        </label>
                                    </div>
                                </td>
                            </tr> -->
                            <tr height="45">
                                <th style="text-align:right;padding-right:10px;">跳转链接:</th>
                                <td><input type="text" class="form-control" size="20" name="jump_url" id="jump_url" /></td>
                            </tr>
                            <tr height="45">
                                <th style="text-align:right;padding-right:10px;">设置库存:</th>
                                <td><input type="number" class="form-control" size="20" name="inventory_max" id="inventory_max" /></td>
                            </tr>
                            <tr height="45">
                                <th style="text-align:right;padding-right:10px;">剩余库存:</th>
                                <td><input type="number" class="form-control" size="20" name="inventory" id="inventory" /></td>
                            </tr>
                            <tr height="45">
                                <th style="text-align:right;padding-right:10px;">总金额:</th>
                                <td><input type="number" class="form-control" size="20" name="total_amount" id="total_amount" /></td>
                            </tr>
                            <tr height="45">
                                <th style="text-align:right;padding-right:10px;">优惠金额:</th>
                                <td><input type="number" class="form-control" size="20" name="discount_amount" id="discount_amount" /></td>
                            </tr>
                        </table>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default pull-left" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary submit_form">确定</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

</section>

<!-- jQuery 3 -->
<script src="js/jquery.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="js/pace.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Select2 -->
<script src="bower_components/select2/dist/js/select2.full.min.js"></script>
<!-- InputMask -->
<script src="plugins/input-mask/jquery.inputmask.js"></script>
<script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>
<!-- SlimScroll -->
<script src="bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script>
<!-- iCheck 1.0.1 -->
<script src="plugins/iCheck/icheck.min.js"></script>
<!-- FastClick -->
<script src="bower_components/fastclick/lib/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>
<script src="js/jquery.dm-uploader.min.js"></script>
<script type="text/javascript">
    $(function() {
        $('.submit_form').click(function() {
            // var _filename = $('#oss_filename').val();
            // if(!_filename) {
            //     alert('图片未上传');
            //     return false;
            // }
            $('#new_banner_form').submit();
        });
        $('.new_banner').click(function() {
            // $('#avatar_preview').attr('src', 'images/noimage.jpg');
            // $('#oss_filename').val('');
            $('#name').val('');
            $('#batch_number').val('');
            $('#jump_url').val('');
            $('#inventory_max').val('');
            $('#inventory').val('');
            $('#total_amount').val('');
            $('#discount_amount').val('');
            $('#modal-add-banner').modal({
                backdrop: 'static',
            });
        });

        $('.edit_coupon').click(function() {
            $('.modal-title').text('修改优惠券');
            // $('#avatar_preview').attr('src', 'images/noimage.jpg');
            // $('#oss_filename').val('');
            var id = $(this).parent().parent().find('.tid').text();
            var name = $(this).parent().parent().find('.tname').text();
            // var avatar = $(this).parent().parent().find('img').attr('src');
            var batch = $(this).parent().parent().find('.batch').text();
            var jump = $(this).parent().parent().find('.jump').text();
            var inventory_max = $(this).parent().parent().find('.inventory_max').text();
            var inventory = $(this).parent().parent().find('.inventory').text();
            var total_amount = $(this).parent().parent().find('.total_amount').text();
            var discount_amount = $(this).parent().parent().find('.discount_amount').text();
            $('#name').val(name);
            $('#edit_id').val(id);
            // if(avatar && avatar.indexOf('.') != -1) {
            //     $('#avatar_preview').attr('src', avatar);
            //     var avatar_arr = avatar.split('/');
            //     var arr_len = avatar_arr.length - 1;
                // $('#oss_filename').val(avatar_arr[arr_len]);
            // }
            $('#batch_number').val(batch);
            $('#jump_url').val(jump);
            $('#inventory_max').val(inventory_max);
            $('#inventory').val(inventory);
            $('#total_amount').val(total_amount);
            $('#discount_amount').val(discount_amount);
            $('#modal-add-banner').modal({
                backdrop: 'static',
            });
        });

        $('.del_banner').click(function() {
            var tid = $(this).parent().attr('tid');
            if(confirm('确认将这个优惠券删除吗？')) {
                location.href = 'red_packet_coupon.php?action=del&tid='+tid;
            }
        });

        $("#drop-area").dmUploader({
            url: 'red_packet_coupon.php?action=upload',
            multiple: false,
            maxFileSize: 3000000,
            allowedTypes: 'image/*',
            extFilter: ['jpg','jpeg','png','gif'],
            onInit: function(){
                console.log('Callback: Plugin initialized');
            },
            onNewFile: function(id, file){
                // When a new file is added using the file selector or the DnD area
                console.log('New file added #' + id);
                if (typeof FileReader !== "undefined"){
                    var reader = new FileReader();
                    var img = $('#avatar_preview');
                    reader.onload = function (e) {
                        img.attr('src', e.target.result);
                    }
                    reader.readAsDataURL(file);
                }
            },
            onBeforeUpload: function(id){
                console.log('start upload ... ' + id);
            },
            onUploadProgress: function(id, percent){
                console.log(id + ' uploading ... ' + percent);
            },
            onUploadSuccess: function(id, data){
                var darr = data.split('|');
                if(darr[0] != 'OK') {
                    alert('图片上传失败，请联系管理员');
                } else {
                    $('#upload_result').text('图片上传成功，文件名：' + darr[1]);
                    $('#oss_filename').val(darr[1]);
                }
            },
            onUploadError: function(id, xhr, status, message){
                alert('图片上传失败，请联系管理员');
            },
            onFileSizeError: function(file){
                alert('图片不可超过3M');
            },
            onFileTypeError: function(file){
                alert('图片类型错误');
            },
            onFileExtError: function(file){
                alert('图片扩展名错误');
            }
        });

        setTimeout(function() {
            $('.alert-success').fadeOut();
            if($('.alert-warning').find('span').html() && $('.alert-warning').find('span').html().length < 60) {
                $('.alert-warning').fadeOut();
            }
        }, 2000);
    });
</script>

</body>
</html>
